#include <vector>
#include <algorithm> // For sort, unique
#include <climits>   // For INT_MAX
using namespace std;
class Solution
{
public:
    vector<vector<int>> minAbsoluteDifference(vector<vector<int>> &grid, int k)
    {
        int m = grid.size();
        int n = grid[0].size();
        int h = m - k + 1, w = n - k + 1;
        vector<vector<int>> ans(h, vector<int>(w));
        for (int r_start = 0; r_start <= m - k; ++r_start)
        {
            for (int c_start = 0; c_start <= n - k; ++c_start)
            {
                vector<int> window;
                for (int i = 0; i < k; ++i)
                {
                    for (int j = 0; j < k; ++j)
                    {
                        window.push_back(grid[r_start + i][c_start + j]);
                    }
                }
                sort(window.begin(), window.end());
                window.erase(unique(window.begin(), window.end()), window.end());

                int res;
                if (window.size() < 2)
                    res = 0;
                else
                {
                    res = INT_MAX;
                    for (size_t i = 1; i < window.size(); ++i)
                        res = min(res, window[i] - window[i - 1]);
                }
                ans[r_start][c_start] = res;
            }
        }
        return ans;
    }
};
